const fnObject = (value) => {
	if (Object.prototype.toString.call(value) === '[object Function]') {
		return value()
	}
	return value || {}
}

export const initTableProps = (tableProps = {}) => {
	tableProps.data = []
	tableProps.total = 0
	tableProps.loading = false
	tableProps.pageNum = 1
	tableProps.pageSize = 100
	return tableProps
}

export const keysSetValue = (obj, value = undefined) => {
	for (const key in obj) {
		obj[key] = value
	}
}

export const manager = ({
	start = true,
	api,
	tableProps,
	defaultParams,
	formatRes,
	onError
}) => {
	// 初始table props数据
	initTableProps(tableProps)

	// 上一次请求的参数
	let resParams = {}
	const _mergeParams = (params) => {
		// 分页参数
		const pageParams = {
			pageNum: tableProps.pageNum,
			pageSize: tableProps.pageSize
		}

		if (params === 'page') {
			return Object.assign(resParams, pageParams)
		}
		resParams = Object.assign(
			pageParams,
			// 强制覆盖参数
			params
		)

		return resParams
	}

	const fetchApi = async (params) => {
		tableProps.loading = true
		try {
			let res = await api(_mergeParams(params))
			// 处理response
			if (formatRes && typeof formatRes === 'function') {
				res = (await formatRes(res)) || res
			}
			if (res && res.code === 200) {
				const {
					record = [],
					totalRecord = 0,
					pageNum = 1,
					pageSize = 100
				} = res.data || {}
				tableProps.data = record?.map((row) =>
					Object.assign(row, { isEdit: false, loading: false })
				)
				tableProps.total = totalRecord
				tableProps.pageNum = pageNum
				tableProps.pageSize = pageSize
			}
		} catch (err) {
			onError?.(err)
		} finally {
			tableProps.loading = false
		}
	}

	tableProps.onSizeChange = (value) => {
		tableProps.pageNum = 1
		tableProps.pageSize = value
		fetchApi('page')
	}

	tableProps.onCurrentChange = (value) => {
		tableProps.pageNum = value
		fetchApi('page')
	}

	if (start) {
		fetchApi(defaultParams)
	}

	const reset = (params) => {
		if (typeof apiParams === 'object') {
			keysSetValue(defaultParams)
		}
		tableProps.pageNum = 1
		tableProps.pageSize = 100
		fetchApi(Object.assign(defaultParams, fnObject(params)))
	}

	const batchUpdateRowValue = (key, newVal) => {
		if (!tableProps?.data?.length) return
		tableProps?.data.forEach((row) => {
			row[key] = newVal
		})
	}

	return {
		tableProps,
		fetchApi,
		reset,
		batchUpdateRowValue
	}
}
